import numpy as np
import talib
class MACD:
    def __init__(self, options):
        self.logger = options.get('logger', None)

    def getStatus(self, data, fastPeriod=12, slowPeriod=26, signalPeriod=9, count=0):
        closeList = []  # 收盘价
        volumeList = []  # 成交量
        for item in data:
            closeList.append(item[4])  # 收盘价
            volumeList.append(item[5])  # 成交量
        macdList = np.array(closeList, dtype=float)
        dif, dea, macd = talib.MACD(macdList, fastperiod=fastPeriod,
                                    slowperiod=slowPeriod, signalperiod=signalPeriod)

        latestIndex = -1 - count
        afterIndex = -2 - count
        # 1、最新收盘数据dif大于dea且前一收盘数据dif小于dea，说明为金叉
        goldStatus = dif[latestIndex] > dea[latestIndex] and dif[afterIndex] < dea[afterIndex]
        # 2、最新收盘数据dif小于dea且前一收盘数据dif大余dea，说明为死叉
        deaStatus = dif[latestIndex] < dea[latestIndex] and dif[afterIndex] > dea[afterIndex]

        if goldStatus:
            side = 'BUY'
            message = '金叉'
        elif deaStatus:
            side = 'SELL'
            message = '死叉'
        else:
            side = 'HOLD'  # 默认为HOLD，即不做买卖操作保持原有操作
            message = '非金叉非死叉，持有仓位'

        message = '''message{message},side：{side}
            dif：{dif}, dea：{dea}, volume：{volume}, macd：{macd}
            dif2：{dif2}, dea2：{dea2}, volume2：{volume2}, macd2：{macd2}
            '''.format(
            message=message, side=side, dif=dif[-1], dea=dea[-1], volume=volumeList[-1], macd=macd[-1], dif2=dif[-2], dea2=dea[-2], volume2=volumeList[-2], macd2=macd[-2])
        self.logger.info(message)
        return side
